/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.x3.purchasing.common;

import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
import org.springframework.transaction.interceptor.TransactionProxyFactoryBean;

/**
 * Class ClassConnection adalah class yang berhubungan dengan database dan koneksi
 * @author Kazao
 */
public class ClassConnection {

    /**
     * Variabel instance dari class ClassConnection
     */
    private static ClassConnection instance;
    private DataSource ds;
    private JdbcTemplate jdbc;
    private DataSourceTransactionManager tm;
    private TransactionProxyFactoryBean tpf;

    public ClassConnection() {
        ds = new JndiDataSourceLookup().getDataSource("java:comp/env/jdbc/purchasing");
        tm = new DataSourceTransactionManager(ds);
        tpf = new TransactionProxyFactoryBean();
        jdbc = new JdbcTemplate(ds);
    }

    /**
     * Instance dari class ClassConnection
     * @return Instance dari class ClassConnection
     */
    private static ClassConnection getInstance() {
        if (instance == null) {
            class ClassConnectionImpl extends ClassConnection {
            }
            instance = new ClassConnectionImpl();
        }
        return instance;
    }

    public static JdbcTemplate getJdbc() {
        return getInstance().jdbc;
    }

    public static DataSourceTransactionManager getTransactionManager() {
        return getInstance().tm;
    }

    public static TransactionProxyFactoryBean getTransactionProxyFactoryBean() {
        return getInstance().tpf;
    }

    public static Connection getConnection() {
        try {
            return getInstance().ds.getConnection();
        } catch (SQLException ex) {
            return null;
        }
    }
}
